#include					<iostream>
#include					"SoundPacket.h"
#include					"Listener.h"

Listener::Listener()
{
	_sample_rate = 48000;
//	_sample_rate = 44100;
	_frames_per_buffer = 480;
	_num_channels = 2;
	_buffer.init(30, _frames_per_buffer * _num_channels);
}

Listener::~Listener()
{
	if (_stream)
		Pa_CloseStream(_stream);
}

static int					recordCallback( const void *inputBuffer, void *outputBuffer,
                              unsigned long framesPerBuffer,
                              const PaStreamCallbackTimeInfo* timeInfo,
                              PaStreamCallbackFlags statusFlags,
                              void *userData)
{
	Listener			*listener = reinterpret_cast<Listener *>(userData);

	return listener->record((const short *) inputBuffer);
}

void					Listener::init()
{
	PaStreamParameters  _inputParameters;

	_inputParameters.device = Pa_GetDefaultInputDevice();
	_inputParameters.channelCount = _num_channels;
	_inputParameters.sampleFormat = paInt16;
	_inputParameters.suggestedLatency = Pa_GetDeviceInfo(_inputParameters.device)->defaultLowInputLatency;
	_inputParameters.hostApiSpecificStreamInfo = NULL;

	int err = Pa_OpenStream(&_stream, &_inputParameters, NULL, _sample_rate,
		_frames_per_buffer, paClipOff, recordCallback, this);
	std::cout << Pa_GetErrorText( err ) << std::endl;
}

void						Listener::start()
{
	PaError		err;

	if (_stream && (err = Pa_IsStreamActive(_stream)) != 1)
	{
		_status = paContinue;
		_buffer.reset();
		_frameIndex = 0;
		err = Pa_StartStream(_stream);
		std::cout << Pa_GetErrorText( err ) << std::endl;
	}
}

void						Listener::stop()
{
	_status = paComplete;
	Pa_StopStream(_stream);
}

int							Listener::record(const short *inputBuffer)
{
	size_t to_calc = _frames_per_buffer * _num_channels;
	short					*buf = 	_buffer.write();
	for (size_t i = 0; i < to_calc; ++i)
		buf[i] = inputBuffer[i];
	emit _readBufferFull();
	return (_status);
}

size_t					Listener::getFPB() const
{
	return _frames_per_buffer;
}

size_t					Listener::getChannelNB() const
{
	return _num_channels;
}

size_t					Listener::getSampleRate() const
{
	return _sample_rate;
}

void					Listener::read(ISoundPacket *packet)
{
	short				*ret = _buffer.read();
	packet->setData(ret);
	packet->setFS(_frames_per_buffer);
	packet->setLen(_frames_per_buffer * _num_channels);
}
